import axios from 'axios'
import router from '@/router'
import { ElMessage } from 'element-plus'
import useUserStore from '@/stores/moudels/userStore'
import pinia from '@/stores'
const request = axios.create({
    baseURL: 'http://121.40.96.76:3000/api', // 设置请求的基础URL
    timeout: 5000, // 设置请求的超时时间
})
let userStore = useUserStore(pinia)
request.interceptors.request.use(config=>{
   
    let token = userStore.token
    if(token) {
        config.headers.Authorization = `Bearea ${token}`
    }
    return config
},(error)=>{
    ElMessage.error("服务器出现问题，请稍后重试")
    return new Promise.reject(new Error(error))
  })

request.interceptors.response.use(res=>{
   
   if(res.data.code==200) {
    return res.data
   }else {
     ElMessage.error(res.data.message)
     return new Promise.reject(new Error(res.data.message))
   }
 
},(error)=>{
   
    if(error.response.status==401) {
        
        router.push('/')
        userStore.logout()
        ElMessage.error('登录已过期，请重新登录')
        return new Promise.reject(new Error('登录已过期，请重新登录'))
    }
    else {
       
        ElMessage.error(error.response.data.message)
        return new Promise.reject(error)
    }
})

export default request
